//
//  WebJavaScriptCore.swift
//  webApp
//
//  Created by Mical_LF on 2017/6/9.
//  Copyright © 2017年 Mical_LF. All rights reserved.
//

import UIKit
import SwiftyJSON
import JavaScriptCore
import Chrysan

@objc protocol WebJavaScriptDelegate: JSExport {
    
    // js调用App的分享
    func share(_ shareInfo: String, _ callback: String)
    // js调用shareToWechat的分享
    func shareToWechat(_ shareInfo: String, _ callback: String)
    // js调用shareToWechatMoments的分享
    func shareToWechatMoments(_ shareInfo: String, _ callback: String)
    // js调用shareToQQ的分享
    func shareToQQ(_ shareInfo: String, _ callback: String)
    // js调用shareToQzone的分享
    func shareToQzone(_ shareInfo: String, _ callback: String)
    
    // js调用App的浏览图片
    func viewPictures(_ picInfo: String, _ viewFirst: Int)
    
    // js调用App的相册
    func xshare(_ browserInfo: String,_  callback: String)
    
    // js调用App的功能后 App再调用js函数执行回调
    func callAddThingCallbackExtern(handleFuncName: String)
}

@objc class WebJavaScriptModel: NSObject, WebJavaScriptDelegate {
    func shareToWechat(_ shareInfo: String, _ callback: String) {
        let jsonData = shareInfo.data(using: String.Encoding.utf8, allowLossyConversion: false)
        let json = JSON(data: jsonData!)
        
//        DispatchQueue.main.async(execute: {
            let url = URL(string: json["image"].string!)
            let imageView = UIImageView()
            //先下载图片
            imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) in
                
            }, completionHandler: { (image, error, cacheType, imageURL) in
                self.shareInfomationToOtherPlace(shareImageItem: image!, sharetitle: json["subject"].string!, shareContent: json["text"].string!, sharePlatform: SSDKPlatformType.subTypeWechatSession, shareUrl:json["url"].string!, callback: callback)
                
            })
            
//        })
    }
    func shareToWechatMoments(_ shareInfo: String, _ callback: String) {
        let jsonData = shareInfo.data(using: String.Encoding.utf8, allowLossyConversion: false)
        let json = JSON(data: jsonData!)
        
        DispatchQueue.main.async(execute: {
            let url = URL(string: json["image"].string!)
            let imageView = UIImageView()
            //先下载图片
            imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) in
                
            }, completionHandler: { (image, error, cacheType, imageURL) in
                self.shareInfomationToOtherPlace(shareImageItem: image!, sharetitle: json["subject"].string!, shareContent: json["text"].string!, sharePlatform: SSDKPlatformType.subTypeWechatTimeline, shareUrl:json["url"].string!, callback: callback)
                
            })
            
        })
    }
    func shareToQQ(_ shareInfo: String, _ callback: String) {
        let jsonData = shareInfo.data(using: String.Encoding.utf8, allowLossyConversion: false)
        let json = JSON(data: jsonData!)
        
        DispatchQueue.main.async(execute: {
            let url = URL(string: json["image"].string!)
            let imageView = UIImageView()
            //先下载图片
            imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) in
                
            }, completionHandler: { (image, error, cacheType, imageURL) in
                self.shareInfomationToOtherPlace(shareImageItem: image!, sharetitle: json["subject"].string!, shareContent: json["text"].string!, sharePlatform: SSDKPlatformType.subTypeQQFriend, shareUrl:json["url"].string!, callback: callback)
                
            })
            
        })
    }
    func shareToQzone(_ shareInfo: String, _ callback: String) {
        let jsonData = shareInfo.data(using: String.Encoding.utf8, allowLossyConversion: false)
        let json = JSON(data: jsonData!)
        
        DispatchQueue.main.async(execute: {
            let url = URL(string: json["image"].string!)
            let imageView = UIImageView()
            //先下载图片
            imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) in
                
            }, completionHandler: { (image, error, cacheType, imageURL) in
                self.shareInfomationToOtherPlace(shareImageItem: image!, sharetitle: json["subject"].string!, shareContent: json["text"].string!, sharePlatform: SSDKPlatformType.subTypeQZone, shareUrl:json["url"].string!, callback: callback)
                
            })
            
        })
    }

    weak var controller: UIViewController?
    weak var jsContext: JSContext?
    //注入的JS方法
    fileprivate var browser: LLPhotoBrowserViewController?

    //MARK: 分享图文
    func share(_ shareInfo: String,_ callback: String) {
        let jsonData = shareInfo.data(using: String.Encoding.utf8, allowLossyConversion: false)
        let json = JSON(data: jsonData!)
        
        DispatchQueue.main.async(execute: {
            let url = URL(string: json["images"].string!)
            let imageView = UIImageView()
            //先下载图片
            imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) in
                
            }, completionHandler: { (image, error, cacheType, imageURL) in
                self.shareInfomationToOtherPlace(shareImageItem: image!, sharetitle: json["subject"].string!, shareContent: json["text"].string!, sharePlatform: SSDKPlatformType.subTypeWechatSession, shareUrl:json["url"].string!, callback: callback)
                
            })
            
        })
    }
    
    //MARK: 编辑并分享图文
    func xshare(_ browserInfo: String, _ callback: String) {
        DispatchQueue.main.async(execute: {

        let jsonData = browserInfo.data(using: String.Encoding.utf8, allowLossyConversion: false)
        let json = JSON(data: jsonData!)
        let imageArray = json["images"]
        
            let currentVC  = self.parentViewController()
            let nav = currentVC?.view.findNavigator()
            var imageUrlArray: [Any] = [Any]()
            //相册
            let photoBrowser = LFPhotoBrowserController()
            for (_,urlStr):(String, JSON) in imageArray {
                imageUrlArray.append(urlStr.string!)
            }
            photoBrowser.bigUrlArray1_0_1 = imageUrlArray
            photoBrowser.shareTitle = json["subject"].string!
            photoBrowser.shareContent = json["text"].string!
            photoBrowser.reloadCollectionView()
            nav?.pushViewController(photoBrowser, animated: true)
        })
    }
    
    //MARK: 浏览图片
    func viewPictures(_ picInfo: String, _ viewFirst: Int) {
        let jsonData = picInfo.data(using: String.Encoding.utf8, allowLossyConversion: false)
        let json = JSON(data: jsonData!)
        let imageArray = json["images"]
        var data: [LLBrowserModel] = []
        var index = 0;
        let currentVC  = self.parentViewController()
        let locationImageView = UIImageView(frame: CGRect(x: SCREEN_WIDTH/2.0, y: SCREEN_HEIGHT/2.0, width: 0, height: 0))
        currentVC?.view.addSubview(locationImageView)
        DispatchQueue.main.async(execute: {
            for (_,urlStr):(String, JSON) in imageArray {
                let url = URL(string: urlStr.string!)
                let imageView = UIImageView()
                //先下载图片
                imageView.kf.setImage(with: url)
                let model = LLBrowserModel.init()
                model.data = imageArray[index].string
                model.sourceImageView = locationImageView
                index += 1
                data.append(model)
            }
            
            
            if data.count == imageArray.count {
                self.browser = LLPhotoBrowserViewController.init(photoArray: data, currentIndex: viewFirst, sheetTitileArray: ["保存到相册"], isOpenQRCodeCheck: true) { (index, imageView, qrcodeString) in
                    print("ActionSheet点击-->下标=\(index); ImageView:\(imageView); qrcodeString:\(String(describing: qrcodeString))")
                    if index == 0 {
                        UIImageWriteToSavedPhotosAlbum(imageView.image!, self, #selector(self.image(image:didFinishSavingWithError:contextInfo:)), nil)
                        self.browser?.chrysan.show(.plain, message:"图片保存成功", hideDelay: 1.5)
                    }
                }
                self.browser?.presentBrowserViewController()
            }
        })
    }
    
    func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject) {
        if error != nil
        {
            print("error!")
            return
        }
    }
    
    //MARK: app调用js的方法实例
    func callAddThingCallbackExtern(handleFuncName: String) {
        let jsHandlerFunc = self.jsContext?.objectForKeyedSubscript("\(handleFuncName)")
        let dict = ["value": "sean", "age": 18] as [String : Any]
        let _ = jsHandlerFunc?.call(withArguments: [dict])
    }
    
    
    //MARK:  扩展方法 打开系统分享
    func shareInfomationToOtherPlace(shareImageItem: UIImage, sharetitle: String, shareContent:String, sharePlatform: SSDKPlatformType, shareUrl: String,callback: String) {
        
        // 1.创建分享参数
        let shareParames = NSMutableDictionary()
        shareParames.ssdkSetupShareParams(byText: shareContent,
                                          images : shareImageItem,
                                          url : NSURL(string:shareUrl) as URL!,
                                          title : sharetitle,
                                          type : SSDKContentType.auto)
        print(sharePlatform, sharePlatform)

        //2.进行分享
        ShareSDK.share(sharePlatform, parameters: shareParames) { (state : SSDKResponseState, nil, entity : SSDKContentEntity?, error :Error?) in
            let currentVC  = self.parentViewController()

            switch state{
                
            case SSDKResponseState.success:
                print("分享成功")
                let jsHandlerFunc = self.jsContext?.objectForKeyedSubscript(callback)
                let dict = ["value": "分享成功了"] as [String : Any]
                let _ = jsHandlerFunc?.call(withArguments: [dict])
                currentVC?.view.chrysan.show(.plain, message:"分享成功了", hideDelay: 1.5)

            case SSDKResponseState.fail:
                print("授权失败,错误描述:\(String(describing: error))")
                let jsHandlerFunc = self.jsContext?.objectForKeyedSubscript(callback)
                let dict = ["value": "分享取消了"] as [String : Any]
                let _ = jsHandlerFunc?.call(withArguments: [dict])
                currentVC?.view.chrysan.show(.plain, message:"分享取消了", hideDelay: 1.5)

            case SSDKResponseState.cancel:  print("操作取消")
                
            default:
                break
            }
        }
    }
    
    func parentViewController() -> UIViewController? {
        
        var result: UIViewController? = nil
        
        var window = UIApplication.shared.keyWindow
        
        if window?.windowLevel != UIWindowLevelNormal {
            let windows = UIApplication.shared.windows
            for tmpWin : UIWindow in windows {
                window = tmpWin
                break
            }
        }
        
        let frontView = window?.subviews[0]
        let nextResponder = frontView?.next
        
        if (nextResponder?.isKind(of: UIViewController.self))! {
            result = nextResponder as? UIViewController
        }else {
            result = window?.rootViewController
        }
        
        return result
    }

}

class WebViewController: UIViewController, UIWebViewDelegate {
    
    var webView: UIWebView!
    var jsContext: JSContext!
    var url: NSURL?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        textJSContext()
        
        addWebView()
        
        self.title = "Web页面"
    }
    
    func textJSContext() {
        
    }
    
    func addWebView() {
        self.webView = UIWebView(frame: self.view.bounds)
        self.view.addSubview(self.webView)
        self.webView.delegate = self
        self.webView.scalesPageToFit = true
        
        //加载本地HTML页面
        if self.url == nil {
            self.url = Bundle.main.url(forResource: "vue_js_demo", withExtension: "html")! as NSURL
        }
        let request = URLRequest(url: self.url! as URL)
        
        self.webView.loadRequest(request)
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        self.jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
        let model = WebJavaScriptModel()
        model.controller = self
        model.jsContext = self.jsContext
        
        //接下，将webJavaScriptModel模型注入到JS方法中，在JS就可以通过WebViewJavaScriptBridge调用我们暴露的方法了。
        self.jsContext.setObject(model, forKeyedSubscript: "WebViewJavascriptBridge" as NSCopying & NSObjectProtocol)
        
        //注册到本地的HTML页面中
        if self.url == nil {
            self.url = Bundle.main.url(forResource: "vue_js_demo", withExtension: "html")! as NSURL
        }
        DispatchQueue.main.async(execute: {
            self.jsContext.evaluateScript(try? String(contentsOf: self.url! as URL, encoding: String.Encoding.utf8))
 
        })
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
